package yang_yi_fan;

/**
 * @Author if
 * @Date 2021-01-23 下午 02:03
 */
public class YANG_YI_FAN_TH_Q1<V> {
    /**
     * 链表实现栈的入栈、出栈、获取栈的长度和获取栈顶元素
     * length是长度，初始化为0
     * top是Node结点类型，表示为栈顶
     */
    private int length;
    private Node<V> top;
    class Node<V>{
        V v;
        Node<V> next;
        public Node(V v, Node<V> next) {
            this.v = v;
            this.next = next;
        }
    }
    //构造器初始化
    public YANG_YI_FAN_TH_Q1() {
        this.length =0;
        this.top=null;
    }
    //入栈
    public void push(V v) {
        //判断元素是否为null
        if (v == null) {
            throw new NullPointerException("放入元素不能为null");
        //100个元素时栈满
        }else if(this.length>=100){
            System.out.println("大于100个元素，栈满了");
            return;
        }
        Node newNode = new Node(v, null);
        //栈空时
        if(length==0){
            this.top=newNode;
        //栈有元素时
        }else{
            newNode.next=this.top.next;
        }
        this.top.next=newNode;
        this.length++;
    }
    //出栈
    public V pop(){
        //栈空抛异常
        if(length==0){
            throw new NullPointerException("栈为空");
        }else{
            //先提前保存好值，等会往下覆盖时值就不会丢失
            V v=this.top.next.v;
            this.top=this.top.next;
            length--;
            return v;
        }
    }
    //获取栈顶元素
    public V getTop(){
        if(length==0){
            throw new NullPointerException("栈为空");
        }
        //栈不是空时，栈顶元素可以进行返回，反之会抛栈空异常
        return this.top.next.v;
    }
    //获取长度
    public int getLength(){
        return length;
    }
    
    public static void main(String[] args) {
        YANG_YI_FAN_TH_Q1 stack=new YANG_YI_FAN_TH_Q1();
        int length=5;
        for(int i=0;i<length;i++){
            stack.push(i+1);
        }
        System.out.println("栈长为 "+stack.getLength());
        System.out.println("栈顶元素为 "+stack.getTop());
        System.out.println("开始出栈");
        for(int i=0;i<length;i++){
            System.out.println("第"+(i+1)+"个元素的值为 "+stack.pop());
        }
        System.out.println("栈长为 "+stack.getLength());
        System.out.println("此时栈空查询栈顶元素抛出异常");
        System.out.println(stack.getTop());
    }
}
